package com.song.shop.udp;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.nio.charset.Charset;

public class UDPServer {
    public static void main(String[] args) {
        DatagramSocket ds = null ;

        try {
            ds = new DatagramSocket( 8089 );
            byte[] data = new byte[1024];
            DatagramPacket dp = new DatagramPacket(data,data.length);
            ds.receive( dp );
            System.out.println(new String(dp.getData()));

            //向客户端发送数据
            InetAddress clientAddress = dp.getAddress();
            int clientPort = dp.getPort();
            System.out.println(clientAddress+"--"+clientPort);
            byte[] responseData = "你好客户端，我是服务端，我已经收到你发送的消息了".getBytes( Charset.forName( "utf-8" ) );
            DatagramPacket backDp = new DatagramPacket( responseData,responseData.length,clientAddress,clientPort );
            ds.send( backDp );
            ds.close();
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            if (ds != null){
                ds.close();
            }
        }

    }
}
